import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store'
import { Notification } from 'element-ui'
import { getToken } from '@/utils/authorization'
// 进度条
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

Vue.use(Router)

NProgress.configure({ showSpinner: false })

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'login',
    component: () =>
      import(
        /* webpackChunkName: "Login-Register" */ '@/views/login-register/index'
      ),
    meta: {
      title: '登录/注册'
    }
  },
  {
    path: '/',
    component: () => import(/* webpackChunkName: "Layout" */ '@/layout'),
    children: [
      {
        path: 'problems',
        name: 'problems',
        component: () =>
          import(/* webpackChunkName: "Home" */ '@/views/problems/index'),
        meta: {
          title: '首页'
        }
      },
      {
        path: 'problems/:problemId',
        name: 'problems/:problemId',
        component: () =>
          import(/* webpackChunkName: "Problems" */ '@/views/problem/index'),
        meta: {
          title: ''
        }
      },
      {
        path: 'account',
        name: 'account',
        component: () =>
          import(/* webpackChunkName: "Account" */ '@/views/account/index'),
        meta: {
          title: '个人中心'
        }
      },
      {
        path: 'coder',
        name: 'coder',
        component: () =>
          import(/* webpackChunkName: "Coder" */ '@/views/coder/index'),
        meta: {
          title: '在线练习'
        }
      },
      {
        path: 'history',
        name: 'history',
        component: () =>
          import(/* webpackChunkName: "History" */ '@/views/history/index'),
        meta: {
          title: '历史记录'
        }
      }
    ]
  }
]

const router = new Router({
  mode: 'history',
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  NProgress.start()
  document.title = `${to.meta.title} - Python IDE`
  if (to.path === '/login' || to.path === '/register') {
    next()
  } else if (to.path === '/coder') {
    next()
  } else {
    const token = getToken()
    if (token === null || token === '' || token === undefined) {
      Notification.error({
        title: '错误',
        message: '您还未登录！',
        position: 'bottom-right'
      })
      store.dispatch('user/logout')
      next('/login')
    } else {
      next()
    }
    NProgress.done()
  }
})

router.afterEach((to, from, next) => {
  if (to.path === '/login') {
    store.dispatch('user/logout')
  }
  NProgress.done()
})

export default router
